<?php

namespace Toplan\PhpSms;

use Cmzz\AliyunCore\Profile\DefaultProfile;
use Cmzz\AliyunCore\DefaultAcsClient;
use Cmzz\AliyunCore\Regions\Endpoint;
use Cmzz\AliyunCore\Regions\EndpointConfig;
use Cmzz\AliyunCore\Regions\EndpointProvider;
use Cmzz\AliyunSms\Sms\Request\V20160927\SingleSendSmsRequest;
use Cmzz\AliyunCore\Exception\ClientException;

/**
 * Class AliyunAgent
 *
 */
class AliyunAgent extends Agent
{

    /**
     * 发送短信服务
     *
     * @param string|array $to 目标手机号
     * @param string $content 发送内容
     * @param $tempId
     * @param array $data 模板变量
     */
    public function sendSms($to, $content = '', $tempId = 0, array $data)
    {
        define('ENABLE_HTTP_PROXY', env('ALIYUN_SMS_ENABLE_HTTP_PROXY', false));
        define('HTTP_PROXY_IP', env('ALIYUN_SMS_HTTP_PROXY_IP', '127.0.0.1'));
        define('HTTP_PROXY_PORT', env('ALIYUN_SMS_HTTP_PROXY_PORT', '8888'));

        $config   = config('phpsms.agents.Aliyun');
        $endpoint = new Endpoint($config['region_id'], EndpointConfig::getregionIds(), EndpointConfig::getProducDomains());
        EndpointProvider::setEndpoints([$endpoint]);
        $iClientProfile = DefaultProfile::getProfile($config['region_id'], $config['access_key'], $config['access_secret']);
        $client         = new DefaultAcsClient($iClientProfile);
        $request        = new SingleSendSmsRequest();

        $to = is_array($to) ? implode(',', $to) : $to;
        $request->setSignName($config['sign_name']);
        $request->setTemplateCode($config['template_code']);
        $request->setRecNum($to);
        $request->setParamString(json_encode(['code' => $data['code'], 'product' => $data['product']]));

        try {
            $response = $client->getAcsResponse($request);
            $this->result(Agent::SUCCESS, true);
            $this->result(Agent::INFO, $response->RequestId);
            $this->result(Agent::CODE, 200);
        } catch (ClientException  $e) {
            logger()->error($e->getErrorCode());
            logger()->error($e->getErrorMessage());
            $this->result(Agent::SUCCESS, false);
        }
    }

    public function sendContentSms($to, $content)
    {

    }

    public function voiceVerify($to, $code, $tempId, array $tempData)
    {

    }

    public function sendTemplateSms($tempId, $to, array $data)
    {

    }
}